﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using COFE.Core.Profile;
using COFE.Core.Lister;
using NUnit.Framework;
using COFE.Core;
using COFE.Core.Entry;

namespace COFE.Core
{
    public static class IEntryConstructorExtension
    {
        /// <summary>
        /// Create an entries.
        /// </summary>
        /// <param name="constructor"></param>
        /// <param name="listerKey"></param>
        /// <param name="parentParseName"></param>
        /// <param name="primPropProvider"></param>
        /// <param name="isFolder"></param>
        /// <param name="flags">Default as ConvertEntry.</param>
        /// <returns></returns>
        public static IInternalFileSystemInfoExA CreateEntry(this IEntryConstructor constructor,
            string listerKey, IPropertyProvider propProvider,
            EntryConstructionFlags flags = EntryConstructionFlags.Default)
        {
            IInternalFileSystemInfoExA retVal;

            if ((flags & EntryConstructionFlags.ConvertEntry) != 0)
            {
                IPropertyProvider convertedPropProvider;
                IVolume converterVolume;
                if (COFEShared.VolumeRegistrar.ConvertEntry(propProvider, 
                    out convertedPropProvider, out converterVolume,  flags))                
                {
                    propProvider = convertedPropProvider;
                    listerKey = converterVolume.ListerKey;
                }
            }

            bool isFolder = ((FileAttributes)propProvider.GetProperty(FileSystemInfoProperties.FileAttributes).Value)
               .HasFlag(FileAttributes.Directory);

            if (isFolder)
                retVal = constructor.CreateDirectory(listerKey, propProvider, flags);
            else retVal = constructor.CreateFile(listerKey, propProvider, flags);

            return retVal;
        }

        public static IInternalFileSystemInfoExA CreateEntry(this IEntryConstructor constructor,
            IPropertyProvider propProvider,
            EntryConstructionFlags flags = EntryConstructionFlags.Default)
        {
            string fullParseName = propProvider.GetProperty(FileSystemInfoProperties.FullParseName).ValueAsString;
            string listerKey, parseName;
            if (!COFEPath.ParseFullParseName(fullParseName, out listerKey, out parseName))
                throw new ArgumentException(parseName + " is not a valid parse name.");
            if (propProvider.IsPropertySupported(FileSystemInfoProperties.SecondaryVolumeKey))
                listerKey = propProvider.GetProperty(FileSystemInfoProperties.SecondaryVolumeKey).ValueAsString;

            return constructor.CreateEntry(listerKey, propProvider, flags);
        }
    }
}
